//
//  LMUserSG.swift
//  WeiBo
//
//  Created by Li MAc on 2018/11/25.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import UIKit

private let accountFile = "useracSG.josn"
class LMUserSG: NSObject {
//访问令牌
    
    @objc var access_token:String? //= "2.002pZ7AH0Ie1bXaa2e0fde70gSxYIC"
    //用户代号
    @objc var uid:String?
    
    //    用户昵称
    @objc var screen_name : String?
    //    用户头像地址（大图），180×180像素
    @objc var avatar_large: String?
    
    //使用者 3 天
    @objc var expires_in : TimeInterval = 0 {
        didSet{
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期处理
    var expiresDate:Date?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    
    override init() {
        super.init()
        guard let path = accountFile.cz_appendDocumentDir(),
        let data = NSData(contentsOfFile: path),
        let dic = try? JSONSerialization.jsonObject(with: data as Data, options: [])as?[String:AnyObject]  else {
            return
        }
        yy_modelSet(with: dic ?? [:])
        
        expiresDate = Date(timeIntervalSinceNow: -3600*24)
        print(expiresDate)
        
        if expiresDate?.compare(Date()) != .orderedDescending{
            print("账户过期")
            access_token = nil
            uid = nil
            _=try? FileManager.default.removeItem(atPath: path)
        }
        print("账户正常")
    }
    
      func saveAccout(){
        //建立模型字典
        guard var dict = self.yy_modelToJSONObject() as? [String:AnyObject] else{
            return
        }
        //需要删除 expires_in的值
        dict.removeValue(forKey: "expires_in")
        //字典序列化
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []), let filepath = ("useracSG.josn" as NSString).cz_appendDocumentDir() else{
            return
        }
        //写入磁盘
        print("++++++\(filepath)")
        (data as NSData).write(toFile: filepath, atomically: true)
        
        
    }
}
